package com.vic.kjlink.simpletools.attachment.model;

import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  @author Vic.xu 附件处理结果类
 *  @description:
 *  @date: 2021/9/17 0017 17:51
 */
public class HandleResult {

    /** 序号对应附件*/
    Map<Integer, Attachment> seq = new HashMap<>();

    /**总文件数*/
    private int count;
    /**成功的个数*/
    private int successNumber;

    /**相同文件名 对应数量*/
    private Map<String, Integer> fileNameNumberMap = new HashMap<>();

    public HandleResult() {

    }

    public void addSuccessNumber() {
        this.successNumber++;
    }

    public String getDesc() {
        StringBuilder sb = new StringBuilder();
        sb.append("<h3>本次处理详情：</h3>")
                .append("<p>总数:").append(count).append("</p>")
                .append("<p>操作成功:").append(successNumber).append("</p>")
                .append("<p>重复文件名情况:").append("</p>");
        if (fileNameNumberMap.isEmpty()) {
            sb.append("无！");
        } else {
            for (Map.Entry<String, Integer> entry : fileNameNumberMap.entrySet()) {
                if (entry.getValue() != null && entry.getValue() > 1) {
                    sb.append(entry.getKey()).append(":").append(entry.getValue()).append("个<br />");
                }
            }
        }
        return sb.toString();
    }


    public HandleResult(List<Attachment> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        count = list.size();

        for (int i = 0; i < count; i++) {
            seq.put(i + 1, list.get(i));
        }
    }


    /**
     * 给文件加上序号  如果文件名重复的话
     * @param originalFilename 源文件名，存在数据库中的 但是没有后缀
     * @param  当前文件名
     * @return
     */
    public String addFileSeq(String originalFilename, String fileName) {
        //文件后缀
        String suffix = "";
        int indexOf = fileName.lastIndexOf(".");
        if (indexOf > -1) {
            suffix = fileName.substring(indexOf, fileName.length());
        }

        Integer num = fileNameNumberMap.get(originalFilename);
        if (num == null) {
            fileNameNumberMap.put(originalFilename, 1);
            return originalFilename + suffix;
        }
        num++;
        fileNameNumberMap.put(originalFilename, num);
        //文件加序号
        originalFilename = originalFilename + "-" + num;

        return originalFilename + suffix;
    }

    public static void main(String[] args) {
        String fileName = "a.jpg";
        int indexOf = fileName.lastIndexOf(".");
        System.out.println(indexOf);
        if (indexOf > -1) {
            System.out.println(fileName.substring(0, indexOf));
            System.out.println(fileName.substring(indexOf + 1, fileName.length()));
        }
    }

}
